package com.to8to.autotask.util;

import static java.util.Calendar.DAY_OF_YEAR;
import static java.util.Calendar.HOUR_OF_DAY;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.SECOND;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import org.elasticsearch.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.commons.utils.DateUtil;
import com.to8to.commons.utils.StringUtil;
import com.to8to.es.util.LogUtil;

/**
 * Utils.java
 * 作 者:atom.liu
 * 版 本:v2.0
 * 日期:2014年11月21日
 * 描 述:通用工具类
 */
public class Utils
{
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);

    private static final SecureRandom random = new SecureRandom();

    /**
     * 获取所需多少天前后的时间点，单位：秒。
     * @days 天数。 正数：之后多少天的时间点； 负数：之前多少天的时间点
     */
    public static int getDayTimePoint(int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.add(DAY_OF_YEAR, days);
        cal.set(HOUR_OF_DAY, 0);
        cal.set(MINUTE, 0);
        cal.set(SECOND, 0);
        return (int) (cal.getTimeInMillis() / 1000);
    }

    public static void main(String[] args)
    {
        System.out.println(getDayTimePoint(-30));
    }

    /**
     * 获取当前时间，单位：秒 
     */
    public static int getCurrentSecond()
    {
        return (int) (System.currentTimeMillis() / 1000);
    }

    /**
     * 获取所需多少小时前后的时间点，单位：秒。
     * @days 天数。 正数：之后多少小时的时间点； 负数：之前多少小时的时间点
     */
    public static int getHourTimePoint(int hours)
    {
        Calendar cal = Calendar.getInstance();
        cal.add(HOUR_OF_DAY, hours);
        cal.set(MINUTE, 0);
        return (int) (cal.getTimeInMillis() / 1000);
    }

    /**
     * 获取当前时间之前N小时的时间点，单位:秒
     * @param hours 小时数
     */
    public static int getHoursAgo(int hours)
    {
        if (hours < 0)
            hours = 0;
        return (int) ((System.currentTimeMillis() - hours * 60 * 60 * 1000L) / 1000);
    }

    /**
     * 判断集合是否为null或者为空
     * @param collection
     * @return true 为null或空。
     */
    public static boolean isNullOrEmpty(Collection<?> collection)
    {
        return collection == null ? true : collection.size() == 0 ? true : false;
    }

    /**
     * 判断map是否为null或者为空
     * @param map
     * @return true 为null或空。
     */
    public static boolean isNullOrEmpty(Map<?, ?> map)
    {
        return map == null ? true : map.size() == 0 ? true : false;
    }

    /**
     * Collection转字符串，默认以逗号分割。简单的对象的集合可以使用该方法。
     */
    public static <T> String collect2Str(Collection<T> collect)
    {
        return collect2Str(collect, ",");
    }

    /**
     * Collection转字符串。简单的对象的集合可以使用该方法。
     * @param collect 集合
     * @param separator 分隔符
     */
    public static <T> String collect2Str(Collection<T> collect, String separator)
    {
        Joiner joiner = Joiner.on(separator == null ? "," : separator);
        return joiner.join(collect);
    }

    /**
     * 拼装字符串 ，使用逗号分割
     */
    public static String append(String str, String... args)
    {
        StringBuilder sb = new StringBuilder(str);
        if (args.length > 0)
            sb.append(",");
        return Joiner.on(",").appendTo(sb, args).toString();
    }

    /**
     * 将数字字符串转换成Int数组
     * @param str 数字组成的字符串
     * @param separator 分隔符
     */
    public static List<Integer> parseIntegerList(String str, String separator)
    {
        List<Integer> list = new ArrayList<Integer>();
        if (StringUtil.isEmpty(str))
            return list;
        for (String s : str.split(separator))
        {
            try
            {
                list.add(Integer.parseInt(s));
            }
            catch (Exception e)
            {
                logger.error("Utils.parseIntegerList异常！ {}\n{}", e, LogUtil.logStackTrace(e));
            }
        }
        return list;
    }

    /**
     * 是否是今天 
     */
    public static boolean isToday(Date date)
    {
        Calendar cal = Calendar.getInstance();
        int today_year = cal.get(Calendar.YEAR);
        int today_day = cal.get(Calendar.DAY_OF_YEAR);

        cal.setTime(date);
        int date_year = cal.get(Calendar.YEAR);
        int date_day = cal.get(Calendar.DAY_OF_YEAR);

        return today_year == date_year && today_day == date_day;
    }

    /**
     * 获取今天的日期字符串 
     */
    public static String getTodayStr()
    {
        return DateUtil.format(new Date(), "yyyy-MM-dd");
    }

    /**
     * 获取当前的时间，用秒表示
     */
    public static int getNowWithSecond()
    {
        return (int) (Calendar.getInstance().getTimeInMillis() / 1000);
    }

    /**
     * 格式化时间 
     */
    public static String formatWithSecond(int second)
    {
        Date date = new Date(second * 1000L);
        return DateUtil.format(date);
    }

    /**
     * 获得时间是周几 
     */
    public static int getWeekday(String str)
    {
        if (str.length() < 10)
            return -1;
        if (str.length() > 10)
            str = str.substring(0, 10);
        long time = DateUtil.parse(str, "yyyy-MM-dd").getTime();
        return getWeekday(time);
    }

    public static int getWeekday(long timestamp)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timestamp);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek - 1 == 0 ? 7 : dayOfWeek - 1;

    }

    /**
     * 获取本月开始的时间点
     */
    public static int getMonthStart()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);

        return (int) (cal.getTimeInMillis() / 1000);
    }

    /**
     * 现在是否是上班时间
     */
    public static boolean isWorkTime()
    {
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        if ((hour >= 9 && hour < 11)
            || (hour >= 14 && hour < 18)
            || (hour == 8 && minute >= 55)
            || (hour == 18 && minute <= 30)
            || (hour == 13 && minute >= 30)
            || (hour == 11 && minute <= 50))
            return true;
        return false;
    }

    /**
     * 获取Host IP Address 
     */
    public static InetAddress getHostAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();)
            {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp())
                    continue;
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements())
                {
                    InetAddress addr = addresses.nextElement();
                    if (addr.isSiteLocalAddress())
                        return addr;
                }
            }
        }
        catch (SocketException e)
        {
            logger.error("Utils.getHostAddress失败！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
        return null;
    }

    /**
     * 获得随机的boolean值
     * @return
     */
    public static boolean getRandomBoolean()
    {
        return random.nextBoolean();
    }
}
